<?php
/**
 * Created by PageList.php
 * Author: LiaoJiangYi
 * Date: 2015/9/24 14:51
 */
namespace Ext;
class PageList
{
    const STR_UNIT = '条';
    const TARGET = '_self';
    public static function toHtml($page,$total,$pageSize=50,$url='')
    {
        $pageSize=intval($pageSize);
        $page=$page?intval($page):1;
        $lastpg=ceil($total/$pageSize); //最后页，也是总页数
        $page=min($lastpg,$page);
        $prepg=(($page-1)<0)?"0":$page-1; //上一页
        $nextpg=($page==$lastpg ? 0 : $page+1); //下一页
        if (isset($_SERVER['QUERY_STRING']))
        {
            $REQUEST_URI=$_SERVER['QUERY_STRING']?$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']:$_SERVER['PHP_SELF'];
        }
        !$url && $url=$_SERVER["REQUEST_URI"]?$_SERVER["REQUEST_URI"]:$REQUEST_URI;
        $_parse_url=parse_url($url);
        isset($_parse_url["query"]) ? $url_query=$_parse_url["query"] : $url_query='';//单独取出URL的查询字串
        if($url_query){
            $url_query=preg_replace("/(^|&)page\=$page/","",$url_query);
            $url=str_replace($_parse_url["query"],$url_query,$url);
            $url.=$url_query?"&page":"page";
        }else {
            $url.="?page";
        }
        $pagenav=" <a href='$url=1' target='".self::TARGET."'>首页</a> ";
        $pagenav.=$prepg?" <a href='$url=$prepg' target='".self::TARGET."'>上一页</a> ":" 上一页 ";
        $flag=0;
        for($i=$page-2;$i<$page;$i++){
            if($i<1) continue;
            $pagenav.="<a href='$url=$i' target='".self::TARGET."'>[$i]</a>";
        }
        $pagenav.="&nbsp;<b>$page</b>&nbsp;";
        for($i=$page+1;$i<=$lastpg;$i++){
            $pagenav.="<a href='$url=$i' target='".self::TARGET."'>[$i]</a>";
            $flag++;
            if($flag==4) break;
        }
        $pagenav.=$nextpg?" <a href='$url=$nextpg' target='".self::TARGET."'>下一页</a> ":" 下一页 ";
        $pagenav.=" <a href='$url=$lastpg' target='".self::TARGET."'>末页</a> ";
        $pagenav.="共".$total.self::STR_UNIT."，".$pageSize.self::STR_UNIT."/页 ";
        $pagenav.=" 共{$lastpg}页";
        (int)$lastpg<2 &&$pagenav='';
        return $pagenav;
    }
}